package javalearning.MultiThreads.news.day02;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池的优势：
 * 1、降低切换的开销
 * 2、实现方式：
 * a、创建线程池对象
 * public static ExecutorService newFixedThreadPool(int nThreads)
 * b、返回的对象是ExecutorService可以执行Runnable和Callable的类
 * c、执行方法：
 * Future<?> submit(Runnable task)
 * <T> Future<T> submit(Callable<T> task)
 * d、结束线程池
 * ExecutorService.
 */
public class ExecutorDemo {
    public static void main(String[] args) {
        // 1、创建线程池对象
        // 2、创建线程对象
        // 3、调用submit方法
        ExecutorService pool = Executors.newFixedThreadPool(2);
        class MY implements Runnable {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 100; i++) {
                        Thread.sleep(100);
                        System.out.println("我是runnable");
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                    }
                } catch (InterruptedException e) {
                    System.out.println("stop");
                }
            }
        }
        ;
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("我是callable");
                Thread.sleep(1000);
                return "Callable";
            }
        };
        pool.submit(new MY());
        pool.submit(new MY());
        System.out.println(pool.isShutdown());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.shutdown();
//        Future<String> future = pool.submit(callable);
//        String s = null;
//        try {
//            s = future.get();
//        } catch (InterruptedException | ExecutionException e) {
//            e.printStackTrace();
//        }
//        System.out.println("进过计算的 = " + s);
        System.out.println("finished");
    }
}
